/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2025-03-10     金鹏       the first version
 */
#include "key.h"

extern short warn_flag;                           /* 求助标志*/
static rt_thread_t key_handl = RT_NULL;           /* 按键线程句柄*/

/*
 * KEY_Scan
 * @Param NULL
 *
 * Change Logs:
 * Date           Author     Notes
 * 2025-3-22       金鹏                按键检测
 */
static unsigned char KEY_Scan(){

    /* 按键按松开标志*/
    static unsigned char key_up=0;

    if(key_up && KEYread==1)
    {
        /* 消抖*/
        rt_thread_mdelay(10);
        key_up=0;

        if(KEYread == 1){
            return 1;
        }
    }
    else if(KEYread == 0){
        key_up=1;
    }

    return 0;
}

/*
 * KEY_Entry
 * @Param NULL
 *
 * Change Logs:
 * Date           Author     Notes
 * 2025-3-22       金鹏               按键模块线程
 */
void KEY_Entry(void *parameter)
{
    /* 保存键值*/
    unsigned char key;

    while(1){
        key = KEY_Scan();
        if(key == 1){
            warn_flag = 1;
            SYN6288_Say_UTF8("说明原因");
        }

        rt_thread_mdelay(10);
    }

}

/*
 * KEY_Test
 * @Param NULL
 *
 * Change Logs:
 * Date           Author     Notes
 * 2025-3-22       金鹏                 按键模块测试
 */
void KEY_Test()
{

    /* 设置为输入模式*/
    rt_pin_mode(KEYget, 1);

    /* 创建key线程*/
    key_handl = rt_thread_create("key",
                                   KEY_Entry,RT_NULL,
                                   ENTRY_STACK_SIZE-512,
                                   ENTRY_PRI,
                                   ENTRY_TICK);

    /* LOG*/
    if(key_handl != RT_NULL){
        rt_kprintf("key thread create successful!!\n");

        /* 启动按键线程*/
        rt_thread_startup(key_handl);
    }else{
        rt_kprintf("key thread create failed!!\n");

        return -RT_ERROR;
    }

    return RT_EOK;
}
